﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.Comm;
using DunSilverlight.ViewModel;
using System.Text.RegularExpressions;
using Telerik.Windows.Controls;
using System.Text;

namespace DunSilverlight.Views
{
    public partial class PhoneCallQuery : Page
    {
        ReportService.ReportServiceClient ser = new ReportService.ReportServiceClient();
        BankService.BankServiceClient bankSer = new BankService.BankServiceClient();
        UserService.UserServiceClient userSer = new UserService.UserServiceClient();
        public PhoneCallQuery()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Report_PhoneCallQuery))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent();


            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            bankSer.GetListByHQLCompleted += new EventHandler<BankService.GetListByHQLCompletedEventArgs>(bankSer_GetListByHQLCompleted);
            loadBank();

            userSer.GetListBySQLCompleted += new EventHandler<UserService.GetListBySQLCompletedEventArgs>(userSer_GetListBySQLCompleted);
            loadOper();

            ser.GetPhoneCallQueryCompleted += new EventHandler<ReportService.GetPhoneCallQueryCompletedEventArgs>(ser_GetPhoneCallQueryCompleted);
        }

        /// <summary>
        /// 读取银行list
        /// </summary>
        private void loadBank()
        {
            bankSer.GetListByHQLAsync("From Company");
        }

        // <summary>
        /// 读取操作员list（用权限判断）
        /// </summary>
        private void loadOper()
        {
            string orgNumber = AppGlobal.CurrentUser.Organization.FullNumber;
            string orgChildNumber = orgNumber + ".%";
            //获取当前机构下的操作员（具有催收权限）
            string sql = string.Format(
                        @" select u.Id,u.Name
                            from User_User as u 
                            left join User_Role as r on u.RoleId=r.Id
                            left join Organization_Organization org on u.OrganizationId = org.Id
                            where 
                                u.isused=1  and 
                                (org.FullNumber like '{0}' or org.FullNumber = '{1}') and 
                                exists(select 1 from User_Role_Right as rr 
                                            inner join User_Right as ur on rr.RightId=ur.Id 
                                        where ur.Number='process_case' and
                                rr.RoleId=r.Id) ", orgChildNumber, orgNumber);

            userSer.GetListBySQLAsync(sql);
        }

        IList<DunLibrary.Client.Company> bankList;
        void bankSer_GetListByHQLCompleted(object sender, BankService.GetListByHQLCompletedEventArgs e)
        {
            int total = 0;
            bankList = JsonSerializerHelper.JsonToEntities<DunLibrary.Client.Company>(e.Result, out total);
            //取出银行分类（非支行）
            cboxBank.ItemsSource = bankList;

        }

        void userSer_GetListBySQLCompleted(object sender, UserService.GetListBySQLCompletedEventArgs e)
        {
            int total = 0;
            var objList = JsonSerializerHelper.JsonToEntities<object[]>(e.Result, out total);
            List<UserModel> userList = objList.Select(c => new UserModel
            {
                Id = int.Parse(c[0].ToString()),
                Name = c[1].ToString()
            }).ToList();

            cboxOper.ItemsSource = userList;

            if (AppGlobal.CurrentUser.Role.Name == "业务员")
            {
                var item = userList.SingleOrDefault(c => c.Id == AppGlobal.CurrentUser.Id);
                if (item != null)
                {
                    cboxOper.SelectedItem = item;
                    cboxOper.IsEnabled = false;
                }
            }
        }


        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (timePeriod.SelectedDate == null)
            {
                Tools.ShowMessage("请选择数据期号!", "", false);
                return;
            }

            if (tbIdCard.Value != null && !string.IsNullOrEmpty(tbIdCard.Value.ToString()))
            {
                string NumericOrLetter = "^[A-Za-z0-9]+$";
                if (!Regex.IsMatch(tbIdCard.Value.ToString(), NumericOrLetter))
                {
                    Tools.ShowMessage("‘身份证号码’输入格式错误!", "只能输入数字和字母!", false);
                    tbIdCard.Value = null;
                    return;
                }
            }

            if (cboxOper.SelectedItem == null && !string.IsNullOrEmpty(cboxOper.Text))
            {
                Tools.ShowMessage("任务负责人输入错误!", "", false);
                return;
            }

            if (cboxBank.SelectedItem == null && !string.IsNullOrEmpty(cboxBank.Text))
            {
                Tools.ShowMessage("银行分类输入错误!", "", false);
                return;
            }


            DateTime selected = timePeriod.SelectedDate.Value;
            int period = int.Parse(selected.ToString("yyyyMM"));

            double? arrealAmountStart = null;
            if (amountStart.Value != null)
            {
                double val = double.Parse(amountStart.Value.ToString());
                if (val > 0.0)
                    arrealAmountStart = val;
            }

            double? arrealAmountEnd = null;
            if (amountEnd.Value != null)
            {
                double val = double.Parse(amountEnd.Value.ToString());
                if (val > 0.0)
                    arrealAmountEnd = val;
            }

            if (arrealAmountStart != null && arrealAmountEnd != null)
            {
                if (arrealAmountEnd < arrealAmountStart)
                {
                    Tools.ShowMessage("‘欠费金额’输入错误!", "最大金额必须大于最小金额!", false);
                    amountStart.Value = amountEnd.Value = null;
                    amountStart.Focus();
                    return;
                }
            }

            int? import = null;
            if (timeImport.SelectedDate != null)
                import = int.Parse(timeImport.SelectedDate.Value.ToString("yyyyMMdd"));

            int? operId = null;
            if (cboxOper.SelectedItem != null)
                operId = int.Parse(cboxOper.SelectedValue.ToString());

            string cardNo = null;
            if (tbCardNo.Value != null)
                cardNo = tbCardNo.Value.ToString();

            string holderName = null;
            if (tbName.Value != null)
                holderName = tbName.Value.ToString();

            string idCard = null;
            if (tbIdCard.Value != null)
                idCard = tbIdCard.Value.ToString();

            int? bankTypeId = null;
            if (cboxBank.SelectedItem != null)
                bankTypeId = int.Parse(cboxBank.SelectedValue.ToString());

            string bankNum = null;
            if (cboxBank.SelectedItem != null)
                bankNum = (cboxBank.SelectedItem as DunLibrary.Client.Company).FullNumber;

            int? subBankId = null;

            string orgNum = null;
            if (AppGlobal.CurrentUser.Organization != null)
                orgNum = AppGlobal.CurrentUser.Organization.FullNumber;
            Tools.ShowMask(true);
            ser.GetPhoneCallQueryAsync(period,import, arrealAmountStart, arrealAmountEnd, operId, cardNo, holderName,
                idCard, bankNum, subBankId, orgNum);

        }

        void ser_GetPhoneCallQueryCompleted(object sender, ReportService.GetPhoneCallQueryCompletedEventArgs e)
        {
            int total = 0;
            var list = JsonSerializerHelper.JsonToEntities<DunLibrary.Report.PhoneCallQuery>(e.Result, out total);
            RadGridView1.ItemsSource = list;
            Tools.ShowMask(false);
        }

        /// <summary>
        /// 重置所有查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            tbAreaNo.Value = null;
            amountStart.Value = amountEnd.Value = null;
            if (cboxOper.SelectedItem != null)
                cboxOper.SelectedItem = null;
            else
                cboxOper.Text = null;
            tbCardNo.Value = null;
            tbName.Value = null;
            tbIdCard.Value = null;

            if (cboxBank.SelectedItem != null)
                cboxBank.SelectedItem = null;
            else
                cboxBank.Text = null;


            RadGridView1.ItemsSource = null;
        }

        

        /// <summary>
        /// 取消全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void noneSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.UnselectAll();
        }

        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void allSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.SelectAll();
        }

        /// <summary>
        /// 催收情况表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void receiveStatistic_Click(object sender, RoutedEventArgs e)
        {
            if (RadGridView1.SelectedItems.Count == 0)
            {
                Tools.ShowMessage("请选择要生成‘催收情况表’的记录", "", false);
                return;
            }
            var list = new List<DunLibrary.Report.PhoneCallQuery>();
            foreach (var item in RadGridView1.SelectedItems)
            {
                list.Add(item as DunLibrary.Report.PhoneCallQuery);
            }


            var q = from i in list
                    group i by
                    new
                    {
                        BankName = i.BankName,
                        CardNo = i.CardNo,
                        CallTime = i.CallTime.ToString("yyyyMMdd"),
                        OperName = i.OperName
                    }
                        into g
                        select g;

            var ll = q.Select(itemGroup => new DunStatistic
            {
                BankName = itemGroup.Key.BankName,
                CardNo = itemGroup.Key.CardNo,
                CallTimeStr = itemGroup.Key.CallTime,
                TypeName = "电话催款",
                Description = itemGroup.Key.OperName + "：" + string.Join("                       ",
                                        itemGroup.OrderBy(c=>c.CallTime).Select(item => string.Format("{0}，{1}{2}。",
                                             item.Contact,
                                             item.ReceiveType,
                                             string.IsNullOrEmpty(item.CallContent) ? "" : string.Format("，（{0}）", item.CallContent)))
                                         )

            }).ToList();

            ll = ll.OrderBy(c => c.BankName).ThenBy(c => c.CardNo).ThenBy(c => c.CallTimeStr).ToList();


            RadGridView rgv = new RadGridView() { AutoGenerateColumns = false };
            rgv.Columns.Add(new GridViewDataColumn {  Header = "银行分类",DataType=typeof(string), MinWidth = 100, DataMemberBinding = new System.Windows.Data.Binding("BankName"), HeaderTextAlignment = System.Windows.TextAlignment.Center });
            rgv.Columns.Add(new GridViewDataColumn { Header = "卡号", DataType = typeof(string), MinWidth = 140, DataMemberBinding = new System.Windows.Data.Binding("CardNo"), HeaderTextAlignment = System.Windows.TextAlignment.Center });
            rgv.Columns.Add(new GridViewDataColumn { Header = "催收日期", DataType = typeof(string), MinWidth = 100, DataMemberBinding = new System.Windows.Data.Binding("CallTimeStr"), HeaderTextAlignment = System.Windows.TextAlignment.Center });
            rgv.Columns.Add(new GridViewDataColumn { Header = "催款方式", DataType = typeof(string), MinWidth = 100, DataMemberBinding = new System.Windows.Data.Binding("TypeName"), HeaderTextAlignment = System.Windows.TextAlignment.Center });
            rgv.Columns.Add(new GridViewDataColumn { Header = "催收情况说明", DataType = typeof(string), MinWidth = 1000, DataMemberBinding = new System.Windows.Data.Binding("Description"), HeaderTextAlignment = System.Windows.TextAlignment.Center });
            rgv.ItemsSource = ll;
            ExportingModel exp = new ExportingModel();
            exp.SelectedExportFormat = "Excel";
            GridViewExportOptions exportOptions = new GridViewExportOptions();
            exportOptions.Format = ExportFormat.Html;
            exportOptions.ShowColumnFooters = false;
            exportOptions.ShowColumnHeaders = true;
            exportOptions.ShowGroupFooters = false;
            exportOptions.Encoding = Encoding.Unicode;
            exp.ExportWithOptions(rgv, exportOptions);
            rgv.ItemsSource = null;
            rgv = null;
        }

        private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnQuery_Click(sender, null);
            }
        }
    }
}
